/*
@Time : 2019/6/11 0011 12:08
@Author : visons
*/
package player_manager

import (
	"cellent_test/svc/player_svc/playerActor"
	"gitee.com/visons/gopkg/sync2/atomic"
	"sync"
)

type playersManager struct {
	sync.Mutex
	playersMap       map[int64]*playerActor.PlayerActor
	playerSessionMap map[int64]*playerActor.PlayerActor
	count            atomic.Int64
}

var manager *playersManager

func NewPlayerManager() *playersManager {
	sync.Once{}.Do(func() {
		manager = &playersManager{}
	})
	return manager
}

func (pm *playersManager) PutPlayer(p *playerActor.PlayerActor) {
	pm.Lock()
	pm.playersMap[p.GetUser().PlayerId] = p
	pm.playerSessionMap[p.GetSession().ID()] = p
	pm.count.Add(1)
	pm.Unlock()
}

func (pm *playersManager) RemovePlayer(p *playerActor.PlayerActor) {
	pm.Lock()
	defer pm.Unlock()
	delete(pm.playersMap, p.GetUser().PlayerId)
	delete(pm.playerSessionMap, p.GetSession().ID())
	pm.count.Dec()

}

func (pm *playersManager) GetPlayerByUserId(userId int64) *playerActor.PlayerActor {
	return pm.playersMap[userId]
}

func (pm *playersManager) GetPlayerBySessionId(sessionId int64) *playerActor.PlayerActor {
	return pm.playerSessionMap[sessionId]
}

func (pm *playersManager) Visit(v func(actor *playerActor.PlayerActor)) {
	for _, actor := range pm.playersMap {
		v(actor)
	}
}

func GetPlayerManager() *playersManager {
	if manager == nil {
		panic("player manager not init")
	}
	return manager
}
